<?php

namespace App\WeChat;

use EasySwoole\HttpClient\Exception\InvalidUrl;
use EasySwoole\HttpClient\HttpClient;
use EasySwoole\Redis\Config\RedisConfig;
use EasySwoole\Redis\Redis;

class WeChatUtil
{
    public function getAccessToken(): string
    {
        $host = '47.116.6.166';//线上内网ip
        if (is_local_dev()) {
            $host = '101.133.208.26';//公网ip
        }
        $redis = new Redis(new RedisConfig([
            'host' => $host,
            'port' => '6379',
            'auth' => '776643',
            'serialize' => RedisConfig::SERIALIZE_NONE
        ]));
        $token = $redis->get('brz_wechat_access_token_mp');
        return strval($token);
    }

    /**
     * 公众号主动发送文字消息
     *
     * @param string $openid
     * @param string $msg
     * @param string $access_token
     */
    public function sendTextMsg(string $openid, string $msg, string $access_token): void
    {
        if (is_local_dev()) {
            echo $msg, PHP_EOL;
        } else {
            $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$access_token}";
            try {
                $cli = new HttpClient($url);
                $cli->postJSON(json_encode([
                    'touser' => $openid,
                    'msgtype' => 'text',
                    'text' => [
                        'content' => $msg
                    ]
                ], JSON_UNESCAPED_UNICODE));
            } catch (InvalidUrl $e) {
                echo $e->getMessage(), PHP_EOL;
            }
        }
    }

    /**
     * 根据openid获取用户unionid
     *
     * @param $access_token
     * @param $openid
     * @param string $field
     * @return string
     */
    public function brzComGetUnionIdByOpenid($access_token, $openid, $field = 'unionid')
    {
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$openid}&lang=zh_CN";
        try {
            $cli = new HttpClient($url);
            $ret = $cli->get();
            $user = json_decode($ret->getBody(), true);  //包含详细的用户信息
            return $user[$field] ?? '';
        } catch (InvalidUrl $e) {
            return '';
        }
    }

    /**
     * 获取昵称快捷方式
     * 当用户已取消关注时返回空字符串
     * @param string $openid
     * @return string
     */
    public function getNickname(string $openid): string
    {
        $accessToken = self::getAccessToken();
        return $this->brzComGetUnionIdByOpenid($accessToken, $openid, 'nickname');
    }

}
